package org.gesplan.controller;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.gesplan.entity.Rol;
import org.gesplan.entity.Section;
import org.gesplan.entity.Staff;
import org.gesplan.exceptions.NonexistentEntityException;
import org.gesplan.exceptions.PreexistingEntityException;
import org.gesplan.util.Utils;

/**
 *
 * @author David
 */
public class StaffJpaController {

    private EntityManagerFactory emf = null;

	
    public StaffJpaController() {
        this.emf = Utils.getEntityManagerFactory();
    }

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    
    public void create(Staff staff) throws PreexistingEntityException, Exception {
        
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Section sectionId = staff.getSectionId();
            if (sectionId != null) {
                sectionId = em.getReference(sectionId.getClass(), sectionId.getId());
                staff.setSectionId(sectionId);
            }
            Rol rolId = staff.getRolId();
            if (rolId != null) {
                rolId = em.getReference(rolId.getClass(), rolId.getId());
                staff.setRolId(rolId);
            }
            em.persist(staff);
            if (sectionId != null) {
                sectionId.getStaffCollection().add(staff);
                em.merge(sectionId);
            }
            if (rolId != null) {
                rolId.getStaffCollection().add(staff);
                em.merge(rolId);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findStaff(staff.getId()) != null) {
                throw new PreexistingEntityException("Staff " + staff + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
        
    }
 
    
    public void edit(Staff staff) throws NonexistentEntityException, Exception {
        
        EntityManager em = null;
        Short id = staff.getId();
        if (findStaff(id) == null) {
            create(staff);
        } else {
            try {
                em = getEntityManager();
                em.getTransaction().begin();

                Staff persistentStaff = em.find(Staff.class, staff.getId());
                Section sectionIdOld = persistentStaff.getSectionId();
                Section sectionIdNew = staff.getSectionId();
                Rol rolIdOld = persistentStaff.getRolId();
                Rol rolIdNew = staff.getRolId();
                if (sectionIdNew != null) {
                    sectionIdNew = em.getReference(sectionIdNew.getClass(), sectionIdNew.getId());
                    staff.setSectionId(sectionIdNew);
                }
                if (rolIdNew != null) {
                    rolIdNew = em.getReference(rolIdNew.getClass(), rolIdNew.getId());
                    staff.setRolId(rolIdNew);
                }
                staff = em.merge(staff);
                if (sectionIdOld != null && !sectionIdOld.equals(sectionIdNew)) {
                    sectionIdOld.getStaffCollection().remove(staff);
                    sectionIdOld = em.merge(sectionIdOld);
                }
                if (sectionIdNew != null && !sectionIdNew.equals(sectionIdOld)) {
                    sectionIdNew.getStaffCollection().add(staff);
                    em.merge(sectionIdNew);
                }
                if (rolIdOld != null && !rolIdOld.equals(rolIdNew)) {
                    rolIdOld.getStaffCollection().remove(staff);
                    rolIdOld = em.merge(rolIdOld);
                }
                if (rolIdNew != null && !rolIdNew.equals(rolIdOld)) {
                    rolIdNew.getStaffCollection().add(staff);
                    em.merge(rolIdNew);
                }
                em.getTransaction().commit();
            } catch (Exception ex) {
                String msg = ex.getLocalizedMessage();
                if (msg == null || msg.length() == 0) {
                    if (findStaff(id) == null) {
                        throw new NonexistentEntityException("The staff with id " + id + " no longer exists.");
                    }
                }
                throw ex;
            } finally {
                if (em != null) {
                    em.close();
                }
            }
        }
        
    }
    

    public void destroy(Short id) throws NonexistentEntityException {
        
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Staff staff;
            try {
                staff = em.getReference(Staff.class, id);
                staff.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The staff with id " + id + " no longer exists.", enfe);
            }
            Section sectionId = staff.getSectionId();
            if (sectionId != null) {
                sectionId.getStaffCollection().remove(staff);
                em.merge(sectionId);
            }
            Rol rolId = staff.getRolId();
            if (rolId != null) {
                rolId.getStaffCollection().remove(staff);
                em.merge(rolId);
            }
            em.remove(staff);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        
    }

    
    public List<Staff> findStaffEntities() {
        return findStaffEntities(true, -1, -1);
    }

    public List<Staff> findStaffEntities(int maxResults, int firstResult) {
        return findStaffEntities(false, maxResults, firstResult);
    }

    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private List<Staff> findStaffEntities(boolean all, int maxResults, int firstResult) {
        
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Staff.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
        
    }

    
    public Staff findStaff(Short id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Staff.class, id);
        } finally {
            em.close();
        }
    }

    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public int getStaffCount() {
        
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Staff> rt = cq.from(Staff.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
        
    }
    
    
}